package md.mru.frontend.controllers;

import md.mru.frontend.utils.AppUserDetails;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCrypt;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import java.io.IOException;
import java.io.Serializable;

/**
 * @author sergiu.marin
 * @since 31/05/2014.
 */
@ManagedBean
@SessionScoped
public class AuthenticationBean implements Serializable {

    private static final long serialVersionUID = -3547675553011253058L;

    AppUserDetails loginUser = null;

    private String loginFailed;
    private String encryptPassword;
    private String password;

    public void initLoginPage() {
        if ("true".equals(loginFailed)) {
            //BeanUtils.addErrorMessage("login_failed_msg");
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "", "Autentificarea a eșuat"));
            loginFailed = null;
        }
    }

    public void login() throws IOException {
        BeanUtils.getExternalContext().dispatch("/do_login");
    }

    public void logout() throws IOException {
        BeanUtils.getExternalContext().dispatch("/do_logout");
    }

    public AppUserDetails getLoginUser() {
        if (loginUser == null) {
            Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            if (principal != null && principal instanceof AppUserDetails) {
                loginUser = (AppUserDetails) principal;
            }
        }
        return loginUser;
    }

    public boolean hasRole(String role) {
        if (getLoginUser() == null || role == null) {
            return false;
        }
        for (GrantedAuthority authority : getLoginUser().getAuthorities()) {
            if (role.equals(authority.getAuthority())) {
                return true;
            }
        }
        return false;
    }

    public void encrypt() {
        encryptPassword = BCrypt.hashpw(password, BCrypt.gensalt());
    }

    public boolean isAdmin() {
        return hasRole("ROLE_ADMIN");
    }

    public boolean isUser() {
        return hasRole("ROLE_USER");
    }

    public void setLoginFailed(String loginFailed) {
        this.loginFailed = loginFailed;
    }

    public String getLoginFailed() {
        return loginFailed;
    }

    public String getEncryptPassword() {
        return encryptPassword;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}
